// @ts-ignore
import { ref, reactive } from 'vue'
// @ts-ignore
import { ElMessage } from 'element-plus'
// @ts-ignore
import { systemAPI } from '../api/system'
// @ts-ignore
import type { User, UserQueryParams } from '../api/system'

// @ts-ignore
export const useUserManagement = () => {
  // 用户管理相关的响应式数据
  // @ts-ignore
  const loading = ref(false)
  // @ts-ignore
  const saving = ref(false)
  // @ts-ignore
  const selectedUsers = ref([])
  // @ts-ignore
  const tableData = ref([])
  // @ts-ignore
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0
  })

  // 表单数据
  // @ts-ignore
  const editingUser = ref({
    id: 0,
    name: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
  })

  // @ts-ignore
  const detailUser = ref({
    id: 0,
    name: '',
    email: '',
    role: 'user',
    status: 'active',
    createdAt: '',
    updatedAt: ''
  })

  // 查询参数
  // @ts-ignore
  const queryParams = reactive({
    page: 1,
    limit: 20,
    name: '',
    email: '',
    role: '',
    status: ''
  })

  // 加载用户列表
  // @ts-ignore
  const loadUsers = async () => {
    // @ts-ignore
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        limit: pagination.limit,
        name: queryParams.name,
        email: queryParams.email,
        role: queryParams.role,
        status: queryParams.status
      }
      
      const response = await systemAPI.getUsers(params)
      
      // 正确处理API响应数据结构
      if (response.data && response.data.data && response.data.data.list) {
        // @ts-ignore
        tableData.value = response.data.data.list
        // @ts-ignore
        pagination.total = response.data.data.pagination.total
      }
    } catch (error: any) {
      console.error('加载用户数据失败:', error)
      ElMessage.error('加载用户数据失败: ' + (error.message || '未知错误'))
    } finally {
      // @ts-ignore
      loading.value = false
    }
  }

  // 搜索用户
  // @ts-ignore
  const handleSearch = () => {
    // @ts-ignore
    pagination.page = 1
    loadUsers()
  }

  // 重置搜索条件
  // @ts-ignore
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      limit: 20,
      name: '',
      email: '',
      role: '',
      status: ''
    })
    loadUsers()
  }

  // 处理选择变化
  // @ts-ignore
  const handleSelectionChange = (selection: any[]) => {
    // @ts-ignore
    selectedUsers.value = selection
  }

  // 显示用户详情
  // @ts-ignore
  const showUserDetail = async (user: any) => {
    try {
      const response = await systemAPI.getUser(user.id.toString())
      // 正确处理API响应数据结构
      if (response.data && response.data.data) {
        // @ts-ignore
        detailUser.value = response.data.data
        // @ts-ignore
        return detailUser.value
      }
    } catch (error: any) {
      ElMessage.error('获取用户详情失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 编辑用户
  // @ts-ignore
  const editUser = async (user: any) => {
    try {
      const response = await systemAPI.getUser(user.id.toString())
      // 正确处理API响应数据结构
      if (response.data && response.data.data) {
        // @ts-ignore
        editingUser.value = { ...response.data.data, password: '' }
        // @ts-ignore
        return editingUser.value
      }
    } catch (error: any) {
      ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 保存用户（创建或更新）
  // @ts-ignore
  const saveUser = async () => {
    try {
      // @ts-ignore
      saving.value = true
      
      if (editingUser.value.id) {
        // 更新用户
        await systemAPI.updateUser(editingUser.value.id.toString(), {
          name: editingUser.value.name,
          email: editingUser.value.email,
          role: editingUser.value.role,
          status: editingUser.value.status,
          ...(editingUser.value.password ? { password: editingUser.value.password } : {})
        })
        ElMessage.success('用户更新成功')
      } else {
        // 创建用户
        await systemAPI.createUser({
          name: editingUser.value.name,
          email: editingUser.value.email,
          password: editingUser.value.password,
          role: editingUser.value.role,
          status: editingUser.value.status
        })
        ElMessage.success('用户创建成功')
      }
      
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      // @ts-ignore
      saving.value = false
    }
  }

  // 删除用户
  // @ts-ignore
  const deleteUser = async (user: any) => {
    try {
      await systemAPI.deleteUser(user.id.toString())
      ElMessage.success('删除成功')
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 批量删除用户
  // @ts-ignore
  const batchDeleteUsers = async (userIds: number[]) => {
    try {
      await systemAPI.batchDeleteUsers(userIds.map(id => id.toString()))
      ElMessage.success('批量删除成功')
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('批量删除失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 批量更新用户状态
  // @ts-ignore
  const batchUpdateUserStatus = async (userIds: number[], status: string) => {
    try {
      // 注意：systemAPI中没有batchUpdateUserStatus方法，这里使用批量更新的方式
      // 我们需要逐个更新用户状态
      const promises = userIds.map(id => 
        systemAPI.updateUser(id.toString(), { status })
      )
      await Promise.all(promises)
      ElMessage.success('批量更新状态成功')
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('批量更新状态失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 重置密码
  // @ts-ignore
  const resetUserPassword = async (userId: number, password: string) => {
    try {
      await systemAPI.updateUser(userId.toString(), { password })
      ElMessage.success('密码重置成功')
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 切换用户状态
  // @ts-ignore
  const toggleUserStatus = async (user: any) => {
    try {
      const newStatus = user.status === 'active' ? 'inactive' : 'active'
      await systemAPI.updateUser(user.id.toString(), { status: newStatus })
      ElMessage.success('状态更新成功')
      loadUsers()
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 显示批量操作
  // @ts-ignore
  const showBatchOperations = (selectedUsers: any[]) => {
    if (selectedUsers.length === 0) {
      ElMessage.warning('请先选择用户')
      return false
    }
    // 这个方法的具体实现应该在组件中完成
    return true
  }

  // 分页相关方法
  // @ts-ignore
  const handleSizeChange = (val: number) => {
    // @ts-ignore
    pagination.limit = val
    // @ts-ignore
    pagination.page = 1
    loadUsers()
  }

  // @ts-ignore
  const handleCurrentChange = (val: number) => {
    // @ts-ignore
    pagination.page = val
    loadUsers()
  }

  // ==================== 用户分组 ====================
  // @ts-ignore
  const loadUserGroups = async () => {
    try {
      const response = await systemAPI.getUserGroups({});
      return response.data?.data || [];
    } catch (error: any) {
      ElMessage.error('加载用户分组失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const createUserGroup = async (groupData: { name: string; description?: string }) => {
    try {
      const response = await systemAPI.createUserGroup(groupData);
      ElMessage.success('分组创建成功');
      return response.data?.data;
    } catch (error: any) {
      ElMessage.error('创建分组失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const updateUserGroup = async (id: number, groupData: { name?: string; description?: string }) => {
    try {
      const response = await systemAPI.updateUserGroup(id.toString(), groupData);
      ElMessage.success('分组更新成功');
      return response.data?.data;
    } catch (error: any) {
      ElMessage.error('更新分组失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const deleteUserGroup = async (id: number) => {
    try {
      await systemAPI.deleteUserGroup(id.toString());
      ElMessage.success('分组删除成功');
      return true;
    } catch (error: any) {
      ElMessage.error('删除分组失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const getGroupMembers = async (groupId: number) => {
    try {
      const response = await systemAPI.getGroupMembers({ groupId });
      return response.data?.data || [];
    } catch (error: any) {
      ElMessage.error('获取分组成员失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const addUserToGroup = async (userId: number, groupId: number) => {
    try {
      const response = await systemAPI.addUserToGroup({ userId, groupId });
      ElMessage.success('用户添加到分组成功');
      return response.data?.data;
    } catch (error: any) {
      ElMessage.error('添加用户到分组失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };

  // @ts-ignore
  const removeUserFromGroup = async (userId: number, groupId: number) => {
    try {
      await systemAPI.removeUserFromGroup({ userId, groupId });
      ElMessage.success('用户从分组中移除成功');
      return true;
    } catch (error: any) {
      ElMessage.error('从分组中移除用户失败: ' + (error.message || '未知错误'));
      throw error;
    }
  };


  return {
    // 数据
    // @ts-ignore
    loading,
    // @ts-ignore
    saving,
    // @ts-ignore
    selectedUsers,
    // @ts-ignore
    tableData,
    // @ts-ignore
    pagination,
    // @ts-ignore
    editingUser,
    // @ts-ignore
    detailUser,
    // @ts-ignore
    queryParams,
    
    // 方法
    // @ts-ignore
    loadUsers,
    // @ts-ignore
    handleSearch,
    // @ts-ignore
    handleReset,
    // @ts-ignore
    handleSelectionChange,
    // @ts-ignore
    showUserDetail,
    // @ts-ignore
    editUser,
    // @ts-ignore
    saveUser,
    // @ts-ignore
    deleteUser,
    // @ts-ignore
    batchDeleteUsers,
    // @ts-ignore
    batchUpdateUserStatus,
    // @ts-ignore
    resetUserPassword,
    // @ts-ignore
    toggleUserStatus,
    // @ts-ignore
    showBatchOperations,
    // @ts-ignore
    handleSizeChange,
    // @ts-ignore
    handleCurrentChange,
    // 用户分组相关方法
    // @ts-ignore
    loadUserGroups,
    // @ts-ignore
    createUserGroup,
    // @ts-ignore
    updateUserGroup,
    // @ts-ignore
    deleteUserGroup,
    // @ts-ignore
    getGroupMembers,
    // @ts-ignore
    addUserToGroup,
    // @ts-ignore
    removeUserFromGroup
  }
}